import 'package:get/get.dart';
import 'package:flutter_easylogger/flutter_logger.dart';

import '../../../../config/router_page_name.dart';
import '../../../../http/http_service.dart';
import '../../../../utils/user_info_utils.dart';

class MerchantHomeLogic extends GetxController {
  // 统计数据
  final pendingOrderCount = 0.obs;
  final totalOrderCount = 0.obs;
  final totalFoodCount = 0.obs;
  
  // 加载状态
  final isLoading = false.obs;
  
  // HTTP服务
  final httpService = HttpService();

  @override
  void onInit() {
    super.onInit();
    loadStatistics();
  }

  // 加载统计数据
  Future<void> loadStatistics() async {
    if (isLoading.value) return;
    
    isLoading.value = true;
    
    try {
      // 获取用户ID
      var loginModel = DataUtils().getLoginModel();
      var userId = loginModel.id;

      if (userId == null) {
        throw Exception('未获取到用户ID');
      }
      
      // 加载订单数据
      final ordersResponse = await httpService.get('/orders', queryParameters: {'userId': userId});
      if (ordersResponse.statusCode == 200) {
        final List<dynamic> orders = ordersResponse.data;
        
        // 计算待处理订单数量（已付款但未完成的订单）
        int pending = 0;
        for (var order in orders) {
          String status = order['status'];
          if (status == 'PAID' || status == 'PREPARING' || status == 'DELIVERING') {
            pending++;
          }
        }
        
        pendingOrderCount.value = pending;
        totalOrderCount.value = orders.length;
      }
      
      // 加载菜品数据
      final menuResponse = await httpService.get('/menu');
      if (menuResponse.statusCode == 200) {
        final List<dynamic> foods = menuResponse.data['foods'];
        totalFoodCount.value = foods.length;
      }
      
      Logger.i('统计数据加载成功');
    } catch (e) {
      Logger.e('统计数据加载失败: $e');
    } finally {
      isLoading.value = false;
    }
  }
  
  // 导航到订单管理页面
  void goToOrderManagement() {
    Get.toNamed(RouterPageName.merchantOrderManagementPage);
  }
  
  // 导航到菜品管理页面
  void goToFoodManagement() {
    Get.toNamed(RouterPageName.merchantFoodManagementPage);
  }
}
